﻿namespace Timo.Common.Extension;

/// <summary>
/// 数字帮助类
/// </summary>
public static class DecimalHelper
{
    /// <summary>
    /// 转中文大写数字
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string ToChineseUpperCase(this decimal value)
    {
        string[] num_list = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
        string[] unit_list = { "分", "角", "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟" };

        decimal money = value;
        if (money == 0)
        {
            return "零元整";
        }

        StringBuilder str_money = new StringBuilder();
        //只取小数后2位



        string str_num = decimal.Truncate(money * 100).ToString();

        int len = str_num.Length;
        int zero = 0;
        for (int i = 0; i < len; i++)
        {
            int num = int.Parse(str_num.Substring(i, 1));
            int unit_num = len - i - 1;

            if (num == 0)
            {
                zero++;
                if (unit_num == 2 || unit_num == 6 || unit_num == 10)
                {
                    if (unit_num == 2 || zero < 4)
                        str_money.Append(unit_list[unit_num]);
                    zero = 0;
                }
            }
            else
            {

                if (zero > 0)
                {
                    str_money.Append(num_list[0]);
                    zero = 0;
                }
                str_money.Append(num_list[num]);
                str_money.Append(unit_list[unit_num]);
            }

        }
        if (zero > 0)
            str_money.Append("整");

        return str_money.ToString();
    }

    /// <summary>
    /// 截取指定位数
    /// </summary>
    /// <param name="d"></param>
    /// <param name="s"></param>
    /// <returns></returns>
    public static decimal ToFixed(this decimal d, int s)
    {
        decimal sp = Convert.ToDecimal(Math.Pow(10, s));
        return Math.Truncate(d) + Math.Floor((d - Math.Truncate(d)) * sp) / sp;
    }


}